use core::arch::asm;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProcessState {
    Ready,
    Running,
    Blocked,
    Terminated,
}

#[derive(Clone, Copy)]
pub struct Process {
    pub id: usize,
    pub state: ProcessState,
    pub stack_pointer: usize,
    pub stack: [u8; 4096],
    pub entry_point: usize,
}

impl Process {
    pub fn new(id: usize, entry_point: usize) -> Self {
        Process {
            id,
            state: ProcessState::Ready,
            stack_pointer: 0,
            stack: [0; 4096],
            entry_point,
        }
    }

    pub fn init_stack(&mut self) {
        // 初始化进程栈，设置初始栈指针
        self.stack_pointer = self.stack.as_ptr() as usize + self.stack.len();
        // 在栈顶设置初始上下文，用于首次切换到该进程
        unsafe {
            let sp = self.stack_pointer as *mut usize;
            // 设置返回地址为进程入口点
            sp.offset(-1).write(self.entry_point);
            // 调整栈指针
            self.stack_pointer = sp.offset(-32) as usize;
        }
    }
}